﻿using System;
using StackExchange.Redis;
using BlockMain_Class;
using Newtonsoft.Json;
using System.Threading;

namespace BlockMain_Check
{
    class Program
    {
        /// <summary>
        /// 共识验证测试 暂时只简单的进行处理 已废弃
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
            {
                ISubscriber sub = redis.GetSubscriber();

                //订阅名为 messages 的通道

                sub.Subscribe("peer", (channel, message) =>
                {

                    //输出收到的消息
                    Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
                    var data = message;//($"[{DateTime.Now:HH:mm:ss}] {message}");
                                       //验证当前数据其他节点是否全部验证通过
                    while (true)
                    {
                        var b = true;
                        var hash = "";
                        for (int i = 1; i <= 4; i = 1)
                        {
                            var val = Cache.Get(i + data);
                            Record r = JsonConvert.DeserializeObject<Record>(val.ToString());
                            if (r.State == 0)
                            {
                                //等待处理
                                b = false;
                            }
                            else if (r.State == -1)
                            {
                                //拒绝 
                            }
                            else {
                                hash = "上链的HASH为："+r.JsonData;
                            }
                        }
                        //共识

                        if (b)
                        {
                            //全部已处理
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {hash}");
                            break;
                        }
                        else
                        {
                            Thread.SpinWait(1000);
                        }
                    }


                });
                Console.WriteLine("已订阅");
                Console.ReadKey();
            }

        }
    }
}
